<?php 

namespace IMT\ServicesBundle\Controller;

use JMS\Serializer\SerializationContext;

use IMT\AttachmentsBundle\Entity\Attachment;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
use FOS\Rest\Util\Codes;

class AttachmentRestController extends Controller
{
	/**
	 * GET /attachment/{eventId}
	 *
	 * @param string $eventId
	 * @return Response
	 */
	public function getAttachmentAction($attachmentId)
	{			
		if(intval($attachmentId) == 0)
	    	throw new \InvalidArgumentException(400, 'L\'id est incorrect : '.$attachmentId);
	    
    	// Récupération de l'attachment
    	$repository = $this->getDoctrine()->getRepository('IMTAttachmentsBundle:Attachment');
   		$attachment = $repository->findOneById($attachmentId);
   		
   		if (!$attachment)
   			throw new NotFoundHttpException('La pièce jointe ayant l\'id '.$attachmentId.' n\'existe pas');
   		
   		
   		// Vérification des droits d'acces
   		$securityContext = $this->get('security.context');   		
   		
   		$context = new SerializationContext();
   		$context->setVersion('1.0');
   		$context->setGroups(array('attachment_details', 'event_list', 'user_list'));
   			   		
		$view = View::create()
			->setStatusCode(200)
			->setData($attachment)
			->setSerializationContext($context);

		return $this->get('fos_rest.view_handler')->handle($view);
	}
	
	/**
	 * Creates a new Thread from the submitted data.
	 *
	 * @param Request $request The current request
	 *
	 * @return View
	 */
	public function postAttachmentAction(Request $request)
	{
		$idAttachment = 0;
	
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		if('POST' == $request->getMethod()){
			$idAttachment = $request->request->get('attachment_id');
			
			$validator = $this->get('validator');
			
			$attachment = null;
						
			$user = $this->get('security.context')->getToken()->getUser();
	
			if($idAttachment == 0){
				$attachment = new Attachment();
				$attachment->setDateCrea(new \DateTime());
			} else {
				$attachment = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($idAttachment);
					
				if(!$attachment)
					throw $this->createNotFoundException('La pièce jointe "'.$idAttachment.'" n\'existe pas');
			}
			
			$attachment->setName($request->request->get('attachment_name'));
			$attachment->setFileBase64($request->request->get('attachment_base64'));
			$attachment->setMime($request->request->get('attachment_mime'));
			$attachment->setExtension($request->request->get('attachment_extension'));
						
			$attachment->setFile(base64_decode($request->request->get('attachment_base64')));
			
			$idUser = intval($request->request->get('attachment_user'));			
			if($idUser){
				$user = $em->getRepository('IMTUserBundle:User')->find($idUser);
				
				if($user){
					$attachment->setUser($user);
				}
			}
			
			$idEvent = intval($request->request->get('attachment_event'));				
			if($idEvent){
				$event = $em->getRepository('IMTEventBundle:BaseEvent')->find($idEvent);
			
				if($event){
					$attachment->setEvent($event);
				}
			}
									
			//return $viewHandler->handle($this->createErrorViewResponse($attachment));
			$errors = $validator->validate($attachment);
			
			if(count($errors) > 0){
				$return['errors'] = $errors;
			
				return $viewHandler->handle($this->createErrorViewResponse($return));
			} else {
				$em = $this->getDoctrine()->getEntityManager();
				$em->persist($attachment);
				$em->flush();
					
				$return['idAttachment'] = $attachment->getId();
			
				return $viewHandler->handle($this->createSuccessViewResponse($return));
			}
		} else {
			throw new MethodNotAllowedException('POST');
		}
	
	}
	
	public function deleteAttachmentAction($id)
	{
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		$entity = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);
		
		$user = $this->get('security.context')->getToken()->getUser();
		
		if (!$entity) {
			throw $this->createNotFoundException('La pièce jointe "'.$id.'" n\'existe pas');
		} 
		
		$em->remove($entity);
		$em->flush();
		
		return $viewHandler->handle($this->createSuccessViewResponse(array('idAttachment' => $id)));
	}
	
	private function createSuccessViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(200)
		->setData($return);
	
		return $view;
	}
	
	private function createErrorViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(Codes::HTTP_BAD_REQUEST)
		->setData($return);
	
		return $view;
	}
}